<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能体流式聊天测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .features {
            padding: 30px;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
        }

        .features h3 {
            color: #333;
            margin-bottom: 15px;
            font-size: 1.3em;
        }

        .feature-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .feature-item {
            background: white;
            padding: 15px;
            border-radius: 10px;
            border-left: 4px solid #4facfe;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .feature-item strong {
            color: #4facfe;
            display: block;
            margin-bottom: 5px;
        }

        .test-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
        }

        .test-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 15px 20px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }

        .test-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
        }

        .chat-container {
            padding: 30px;
        }

        .input-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .input-group input {
            flex: 1;
            padding: 15px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        .input-group input:focus {
            outline: none;
            border-color: #4facfe;
        }

        .send-btn {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 16px;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .send-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 15px rgba(79, 172, 254, 0.3);
        }

        .send-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .chat-messages {
            max-height: 500px;
            overflow-y: auto;
            border: 2px solid #e9ecef;
            border-radius: 15px;
            padding: 20px;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 20px;
            padding: 15px;
            border-radius: 15px;
            max-width: 80%;
            word-wrap: break-word;
        }

        .user-message {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            margin-left: auto;
            text-align: right;
        }

        .bot-message {
            background: white;
            border: 2px solid #e9ecef;
            margin-right: auto;
        }

        .streaming {
            border-left: 4px solid #4facfe;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0% { border-left-color: #4facfe; }
            50% { border-left-color: #00f2fe; }
            100% { border-left-color: #4facfe; }
        }

        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 8px;
            font-size: 14px;
        }

        .status.info {
            background: #e3f2fd;
            color: #1976d2;
            border-left: 4px solid #2196f3;
        }

        .status.error {
            background: #ffebee;
            color: #c62828;
            border-left: 4px solid #f44336;
        }

        .status.success {
            background: #e8f5e8;
            color: #2e7d32;
            border-left: 4px solid #4caf50;
        }

        .timestamp {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
        }

        .clear-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            margin-left: 10px;
        }

        .clear-btn:hover {
            background: #c82333;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 智能体流式聊天测试</h1>
            <p>体验实时流式输出的智能体对话系统</p>
        </div>

        <div class="features">
            <h3>🚀 智能体功能特性</h3>
            <div class="feature-grid">
                <div class="feature-item">
                    <strong>🌐 网络搜索</strong>
                    <span>实时获取最新信息</span>
                </div>
                <div class="feature-item">
                    <strong>⏰ 时间查询</strong>
                    <span>获取当前时间信息</span>
                </div>
                <div class="feature-item">
                    <strong>🧮 数学计算</strong>
                    <span>执行复杂数学运算</span>
                </div>
                <div class="feature-item">
                    <strong>🌤️ 天气查询</strong>
                    <span>获取城市天气信息</span>
                </div>
                <div class="feature-item">
                    <strong>💭 对话记忆</strong>
                    <span>记住对话上下文</span>
                </div>
                <div class="feature-item">
                    <strong>⚡ 流式输出</strong>
                    <span>实时显示生成过程</span>
                </div>
            </div>

            <h3>🎯 快速测试</h3>
            <div class="test-buttons">
                <button class="test-btn" onclick="testQuery('现在几点了？')">⏰ 时间查询测试</button>
                <button class="test-btn" onclick="testQuery('计算 123 * 456 + 789')">🧮 数学计算测试</button>
                <button class="test-btn" onclick="testQuery('北京今天天气怎么样？')">🌤️ 天气查询测试</button>
                <button class="test-btn" onclick="testQuery('搜索最新的人工智能发展趋势')">🌐 网络搜索测试</button>
                <button class="test-btn" onclick="testQuery('你好，我是新用户，请介绍一下你的功能')">👋 功能介绍测试</button>
                <button class="test-btn" onclick="testQuery('帮我分析一下当前科技行业的发展状况，需要最新数据')">🔍 综合分析测试</button>
            </div>
        </div>

        <div class="chat-container">
            <div class="input-group">
                <input type="text" id="messageInput" placeholder="输入您的问题..." onkeypress="handleKeyPress(event)">
                <button class="send-btn" id="sendBtn" onclick="sendMessage()">发送</button>
                <button class="clear-btn" onclick="clearChat()">清空</button>
            </div>
            
            <div class="chat-messages" id="chatMessages"></div>
        </div>
    </div>

    <script>
        let isStreaming = false;
        let conversationId = Math.floor(Math.random() * 1000000);
        let userId = 1;

        function testQuery(query) {
            document.getElementById('messageInput').value = query;
            sendMessage();
        }

        function handleKeyPress(event) {
            if (event.key === 'Enter' && !isStreaming) {
                sendMessage();
            }
        }

        function addMessage(content, isUser = false, isStreaming = false) {
            const messagesContainer = document.getElementById('chatMessages');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isUser ? 'user-message' : 'bot-message'} ${isStreaming ? 'streaming' : ''}`;
            
            const contentDiv = document.createElement('div');
            contentDiv.innerHTML = content.replace(/\n/g, '<br>');
            messageDiv.appendChild(contentDiv);
            
            const timestampDiv = document.createElement('div');
            timestampDiv.className = 'timestamp';
            timestampDiv.textContent = new Date().toLocaleTimeString();
            messageDiv.appendChild(timestampDiv);
            
            messagesContainer.appendChild(messageDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            
            return messageDiv;
        }

        function addStatus(message, type = 'info') {
            const messagesContainer = document.getElementById('chatMessages');
            const statusDiv = document.createElement('div');
            statusDiv.className = `status ${type}`;
            statusDiv.textContent = message;
            messagesContainer.appendChild(statusDiv);
            messagesContainer.scrollTop = messagesContainer.scrollHeight;
            return statusDiv;
        }

        async function sendMessage() {
            const input = document.getElementById('messageInput');
            const sendBtn = document.getElementById('sendBtn');
            const message = input.value.trim();
            
            if (!message || isStreaming) return;
            
            // 添加用户消息
            addMessage(message, true);
            input.value = '';
            
            // 设置流式状态
            isStreaming = true;
            sendBtn.disabled = true;
            sendBtn.textContent = '生成中...';
            
            // 创建机器人消息容器
            const botMessageDiv = addMessage('', false, true);
            const contentDiv = botMessageDiv.querySelector('div');
            
            try {
                const response = await fetch('/api/v1/chat/agent/stream', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        message: message,
                        conversation_id: conversationId,
                        user_id: userId
                    })
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let fullContent = '';
                
                while (true) {
                    const { done, value } = await reader.read();
                    
                    if (done) break;
                    
                    const chunk = decoder.decode(value);
                    const lines = chunk.split('\n');
                    
                    for (const line of lines) {
                        if (line.startsWith('data: ')) {
                            const data = line.slice(6);
                            
                            if (data === '[DONE]') {
                                // 流式输出完成
                                botMessageDiv.classList.remove('streaming');
                                continue;
                            }
                            
                            try {
                                const parsed = JSON.parse(data);
                                
                                if (parsed.error) {
                                    addStatus(`错误: ${parsed.error}`, 'error');
                                    break;
                                }
                                
                                if (parsed.content) {
                                    fullContent += parsed.content;
                                    contentDiv.innerHTML = fullContent.replace(/\n/g, '<br>');
                                    
                                    // 自动滚动到底部
                                    const messagesContainer = document.getElementById('chatMessages');
                                    messagesContainer.scrollTop = messagesContainer.scrollHeight;
                                }
                            } catch (e) {
                                console.warn('解析数据失败:', data);
                            }
                        }
                    }
                }
                
                addStatus('✅ 回答完成', 'success');
                
            } catch (error) {
                console.error('发送消息失败:', error);
                addStatus(`❌ 发送失败: ${error.message}`, 'error');
                botMessageDiv.remove();
            } finally {
                // 重置状态
                isStreaming = false;
                sendBtn.disabled = false;
                sendBtn.textContent = '发送';
            }
        }

        function clearChat() {
            document.getElementById('chatMessages').innerHTML = '';
            addStatus('💬 聊天记录已清空', 'info');
        }

        // 页面加载完成后的初始化
        document.addEventListener('DOMContentLoaded', function() {
            addStatus('🎉 智能体流式聊天系统已就绪！', 'success');
            addStatus(`📝 对话ID: ${conversationId} | 用户ID: ${userId}`, 'info');
        });
    </script>
</body>
</html>